<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{ updataFull, updataDialogWidth }"
      :fullscreen="isfullscreen"
      :width="setDialogWidth('1200px')"
      :visible="visible"
      :title="type == 'edit' ? $t('EDIT_FIBER_CABLE') : $t('CABLE_SEGMENT_DETAIL')"
      class="editCabledialog"
      @open="open"
      @close="close"
    >
      <div class="pb-10">
        <div class="table-container">
          <!-- 这里放置表头 -->
          <div class="table-header">
            <div class="column" style="width: 80px">{{ $t('SEQUENCE') }}</div>
            <div
              v-for="column in tableHead"
              :key="column.prop"
              class="column"
              :class="column.className ? column.className : ''"
              :style="[column.className ? '' : { flex: 1 }]"
            >
              <el-checkbox
                v-if="column.prop === 'layingtypes' && type == 'edit'"
                v-model="checkedAll"
                class="checkedAll"
                @change="changeAll"
              />
              <span
                :class="
                  (column.prop === 'segmentCableName' || column.prop === 'layingtypes') &&
                    type == 'edit'
                    ? 'icon-start flex-1'
                    : ''
                "
              >{{ $t(column.label) }}</span>
              <span
                v-if="column.prop === 'erectMethod' && type == 'edit'"
                class="el-icon-edit icon-font ml-5"
                @click="showMethodEdit = true"
              />
            </div>
          </div>

          <!-- 这里放置表体 -->
          <div class="table-tr" @click="cellClick">
            <div v-for="(item, index) in tableData" :key="item.id" class="row">
              <div class="cell text-center" style="width: 80px">{{ index + 1 }}</div>
              <div class="cell w-140 segmentName">
                <el-input
                  v-if="type == 'edit'"
                  v-model="item.segmentName"
                  :class="item.isNameEmpty ? 'input__inner' : ''"
                  maxlength="101"
                  :placeholder="$t('ENTER_CABLE_SEGMENT_NAME')"
                />
                <span v-if="type == 'view'">{{ item.segmentName }}</span>
                <div v-if="item.isNameEmpty" class="form-item__error w-100">
                  {{ $t('ENTER_CABLE_SEGMENT_NAME') }}
                </div>
              </div>
              <div class="cell w-140">{{ item.startPointName }}</div>
              <div class="cell w-140">{{ item.endPointName }}</div>
              <div class="cell w-140">{{ item.cableName }}</div>
              <div class="cell w-180 erectMethodName">
                <div v-if="type == 'edit'" class="flex align-center w-100">
                  <el-checkbox v-model="item.checked" />
                  <div
                    class="select-holder flex ml-10"
                    data-type="type"
                    :data-id="item.id"
                    :class="item.isempty ? 'error' : ''"
                  >
                    <span class="flex-1" :class="item.erectMethodName ? '' : 'placeholder'">{{
                      item.erectMethodName || $t('PLEASE_SELECT_LAYINGMETHOD2')
                    }}</span>
                    <i class="el-icon-arrow-down" />
                  </div>
                </div>
                <span v-if="type == 'view'">{{ item.erectMethodName }}</span>
                <div v-if="item.isempty" class="form-item__error w-100" style="padding-left: 35px">
                  {{ $t('PLEASE_SELECT_LAYINGMETHOD2') }}
                </div>
              </div>
              <div class="cell w-180">
                <div
                  v-if="
                    item['erectMethodName'] &&
                      layingmethods.filter(i => i.parentId === item['erectMethod']).length &&
                      type == 'edit'
                  "
                  class="select-holder flex"
                  data-type="method"
                  :data-id="item.id"
                  :data-typeid="item.erectMethod"
                >
                  <span class="flex-1" :class="item.layMethodName ? '' : 'placeholder'">{{
                    item.layMethodName || $t('PLEASE_SELECT_LAYINGMETHOD')
                  }}</span>
                  <i class="el-icon-arrow-down" />
                </div>
                <span v-if="type == 'view'">{{ item.layMethodName }}</span>
              </div>
              <div class="cell segmentLength" style="flex: 1">
                <el-input
                  v-if="type == 'edit'"
                  v-model.trim="item.segmentLength"
                  :class="item.iserror ? 'input__inner' : ''"
                  :placeholder="$t('FIBER_LENGTH')"
                  @input="changeInput($event, item)"
                />
                <span v-if="type == 'view'">{{ item.segmentLength }}</span>
                <div v-if="item.iserror" class="form-item__error w-100">{{ item.errormsg }}</div>
              </div>
            </div>
            <NullData v-if="tableData.length === 0" :title="$t('NO_FIBER_CABLE_SECTION')" />
          </div>
        </div>
        <!--批量设置-->
        <div v-if="type == 'edit' && cableList.length" class="flex align-center mt-10">
          <div style="width: 640px">
            <span style="width: 200px">{{ $t('BATCH_SETTINGS') }}：</span>
          </div>
          <div class="flex-1">
            <el-select
              v-model="patchCheck"
              filterable
              style="width: 180px"
              clearable
              :placeholder="$t('PLEASE_SELECT_LAYINGMETHOD2')"
              @change="changePatch"
            >
              <el-option
                v-for="obj in erectMethods"
                :key="obj.code"
                :label="obj.name"
                :value="obj.code"
              />
            </el-select>
          </div>
        </div>
      </div>
      <!--下拉选择-->
      <div v-show="showSelect" id="selectDivCable">
        <el-select
          id="select"
          ref="testSelect"
          v-model="activeCurVal.id"
          filterable
          size="mini"
          @change="selectChange"
          @visible-change="visibleChange"
        >
          <el-option
            v-for="obj in activeList"
            :key="obj.code"
            :label="obj.name"
            :value="obj.code"
          />
        </el-select>
      </div>
      <div slot="footer">
        <template v-if="type === 'edit' && cableList.length">
          <el-button size="mini" @click="close">{{ $t('CANCEL') }}</el-button>
          <el-button size="mini" type="primary" @click="$debounce(save)">{{
            $t('SAVE')
          }}</el-button>
        </template>
        <el-button v-else size="mini" @click="close">{{ $t('CLOSE') }}</el-button>
      </div>
    </el-dialog>

    <!--编辑敷设方法-->
    <EditCableMethod
      :erect-methods="erectMethods"
      :layingmethods="layingmethods"
      :visible="showMethodEdit"
      @close="closeLayMethod"
    />
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { deepClone } from '@/utils/common'
  import CableSegmentApi from '@/api/oen/CableSegmentApi'
  import BizDictApi from '@/api/basebiz/BizDictApi'
  import EditCableMethod from './EditCableMethod'
  export default {
    components: {
      EditCableMethod
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      },
      cableList: {
        type: Array,
        default: () => []
      },
      type: {
        type: String,
        default: 'edit'
      }
    },
    data() {
      return {
        checkedAll: false,
        tableHead: [
          {
            label: 'CABLESEGMENTNAME',
            prop: 'segmentCableName',
            className: 'w-140'
          },
          {
            label: 'FROM',
            prop: 'start',
            className: 'w-140'
          },
          {
            label: 'TO_WORD',
            prop: 'end',
            className: 'w-140'
          },
          {
            label: 'AFFILIATED_CABLE',
            prop: 'segmentName',
            className: 'w-140'
          },
          {
            label: 'LAYING_METHOD',
            prop: 'layingtypes',
            className: 'w-180'
          },
          {
            label: 'CABLE_LAY_METHOD',
            prop: 'erectMethod',
            className: 'w-180'
          },
          {
            label: 'FIBER_LENGTH',
            prop: 'segmentLength'
          }
        ],
        tableData: [],
        showMethodEdit: false,
        activeCurVal: {
          type: '',
          id: ''
        },
        rowId: '',
        activeList: [],
        showSelect: false,
        patchCheck: '',
        layingmethods: [] // 敷设方法
      }
    },
    inject: ['parentVM'],
    computed: {
      ...mapGetters(['dictList']),
      erectMethods() {
        // 敷设方式
        const list = deepClone(this.dictList.LAYING_METHOD || [])
        list.forEach(i => {
          i.code = i.value
          i.name = i.label
        })
        return list
      }
    },
    created() {
      this.getCableLayMethods()
    },
    methods: {
      changeInput(val, item) {
        const reg = /^(0|[1-9]\d*)(\.\d{1,3})?$/
        item.iserror = false
        if (!/^\s*$/.test(val) && !reg.test(val)) {
          item.iserror = true
          item.errormsg = this.$t('ONLY_POSITIVE_NUMBERS_3')
          return
        }
        if (Number(val) > this.rowData.cableLength) {
          item.iserror = true
          item.errormsg = this.$t('LENGTH_LESSTHANEQUAL_CABLELENGTH')
        }
      },
      async getCableLayMethods() {
        // 获取敷设方法列表
        const res = await BizDictApi.getByType({ type: 'CABLE_LAY_METHOD' })
        if (Array.isArray(res)) {
          const arr1 = res.filter(i => !i.update)
          const arr2 = res.filter(i => i.update)
          this.layingmethods = [...arr1, ...arr2]
        }
      },
      initTableData() {
        // 初始化当前光缆段列表数据
        const list = []
        console.log('this.cableList-----', this.cableList, this.type)
        this.cableList.forEach(item => {
          const erectObj = this.erectMethods.find(i => i.code === item.erectMethod)
          const layObj = this.layingmethods.find(i => i.code === item.layMethod)
          list.push({
            ...item,
            cableName: this.rowData.cableName,
            segmentName: item.segmentName || item.startPointName + '-' + item.endPointName,
            erectMethodName: (erectObj && erectObj.name) || '',
            layMethodName: (layObj && layObj.name) || '',
            checked: false,
            isempty: false,
            isNameEmpty: false,
            iserror: false,
            errormsg: ''
          })
        })
        this.checkedAll = false
        this.tableData = list
      },
      cellClick(event) {
        const target = event.target
        const cellbox = target.parentNode
        if (!cellbox.dataset.type) return
        this.showSelect = false
        this.activeList = []
        this.rowId = cellbox.dataset.id
        this.activeCurVal.type = cellbox.dataset.type
        const obj = this.tableData.find(i => i.id === this.rowId)
        console.log('obj---------', obj)
        if (cellbox.dataset.type === 'type') {
          this.activeCurVal.id = !obj || !obj.erectMethod ? '' : obj.erectMethod
          this.activeList = this.erectMethods
        } else {
          const list = this.layingmethods.filter(i => i.parentId === cellbox.dataset.typeid)
          this.activeList = list
          // 判断如果敷设方法被删除 光缆段内清空对应敷设方法选项 同时清空列表layMethod的值
          if (!obj || !obj.layMethod || !obj.layMethodName) {
            this.activeCurVal.id = ''
            obj.layMethod = ''
          } else {
            this.activeCurVal.id = obj.layMethod
          }
        }

        this.$nextTick(() => {
          const selectDiv = document.getElementById('selectDivCable')
          selectDiv.style.top = cellbox.getBoundingClientRect().top + 'px'
          selectDiv.style.left = cellbox.getBoundingClientRect().left + 'px'
          selectDiv.style.width = cellbox.getBoundingClientRect().width + 'px'
          this.$refs.testSelect.toggleMenu()
          this.showSelect = true
          this.$nextTick(() => {
            document.getElementById('select').focus()
          })
        })
      },
      selectChange(val) {
        const index = this.tableData.findIndex(i => i.id === this.rowId)
        const obj = this.activeList.find(j => j.code === val)
        let key, keyid
        if (this.activeCurVal.type === 'type') {
          key = 'erectMethodName'
          keyid = 'erectMethod'
          this.tableData[index].layMethod = ''
          this.tableData[index].layMethodName = ''
        } else {
          key = 'layMethodName'
          keyid = 'layMethod'
        }
        const data = { ...this.tableData[index], [key]: obj.name, [keyid]: obj.code }
        this.$set(this.tableData, index, data)
        this.selectBlur()
      },
      visibleChange(data) {
        if (data === false) {
          this.selectBlur()
        }
      },
      selectBlur() {
        document.getElementById('select').blur()
        this.$refs.testSelect && this.$refs.testSelect.blur()
        this.$nextTick(() => {
          this.showSelect = false
        })
      },
      changePatch(val) {
        this.tableData.forEach(item => {
          if (item.checked) {
            const obj = val ? this.erectMethods.find(i => i.code === val) : {}
            item.erectMethodName = obj.name || ''
            item.erectMethod = obj.code || ''
            item.layMethod = ''
            item.layMethodName = ''
          }
        })
      },
      changeAll(val) {
        if (val) {
          this.tableData.forEach(item => {
            item.checked = true
          })
          return
        }
        this.tableData.forEach(item => {
          item.checked = false
        })
      },
      open() {
        this.initTableData()
      },
      save() {
        for (let i = 0; i < this.tableData.length; i++) {
          const item = this.tableData[i]
          item.isempty = false
          item.isNameEmpty = false
          item.iserror = false
          if (!item['segmentName']) {
            item.isNameEmpty = true
          }
          if (!item['erectMethodName']) {
            item.isempty = true
          }
          const reg = /^(0|[1-9]\d*)(\.\d{1,3})?$/
          if (item.segmentLength && !reg.test(item.segmentLength)) {
            item.iserror = true
          }
          if (Number(item.segmentLength) > this.rowData.cableLength) {
            item.iserror = true
            item.errormsg = this.$t('LENGTH_LESSTHANEQUAL_CABLELENGTH')
          }
        }

        const isempty = this.tableData.some(item => !item.segmentName || !item.erectMethodName)
        if (isempty) {
          this.$message.error(this.$t('NAME_LAYINGMETHOD_CANNOT_EMPTY'))
          return
        }
        if (this.tableData.some(item => item.iserror)) {
          return
        }
        const params = {
          cableId: this.rowData.cableId,
          cableSegments: this.tableData,
          cableName: this.rowData.cableName
        }
        CableSegmentApi.modify({ ...params, logParams: { actionName: 'editCableSegment', functionName: this.parentVM.functionName }})
          .then(res => {
            if (res) {
              this.$message.success(this.$t('SAVE_SUCCESS'))
              this.patchCheck = ''
              this.close(true)
            } else {
              this.$message.success(this.$t('SAVEFAILED'))
            }
          })
          .catch(() => {})
      },
      async closeLayMethod(load) {
        this.showMethodEdit = false
        if (load === 'load') {
          await this.getCableLayMethods()
          this.initTableData()
        }
      },
      close(load) {
        this.tableData = []
        this.$emit('close', load)
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';

  /* CSS样式 */
  .editCabledialog {
    .w-140 {
      width: 140px;
    }

    .w-180 {
      width: 180px;
    }
    .error,
    .input__inner .el-input__inner {
      border: 1px solid #f56c6c !important;
    }
    .form-item__error {
      font-size: 10px;
      color: #f56c6c;
    }
    .el-dialog__body {
      padding-top: 0 !important;
    }

    .table-container {
      width: 100%;

      /* 设置容器宽度 */
      @include themeify {
        border: 1px solid themed('tableBorderColor');
      }

      .table-header {
        width: 100%;
        display: flex;
        align-items: center;

        @include themeify {
          background-color: themed('dialogBgColor');
          border-bottom: 1px solid themed('tableBorderColor');
          box-shadow: inset 6px 0px 27px 0px rgba(153, 153, 153, 0.3);
        }

        .column {
          height: 35px;
          min-height: 35px;
          padding: 5px;
          box-sizing: border-box;
          font-size: 14px;
          display: flex;
          align-items: center;
          justify-content: center;

          @include themeify {
            border-right: 1px solid themed('tableBorderColor');
            background-color: themed('tableBgThColor');
          }

          &:last-child {
            border: 0;
          }

          .icon-start {
            position: relative;
            text-align: center;
          }

          .icon-start:before {
            content: '*';
            color: #f56c6c;
            position: absolute;
            transform: translateY(5px) translateX(-10px);
          }
        }
      }
    }

    .table-tr {
      width: 100%;
      height: calc(50vh - 100px);
      overflow: auto;

      .row {
        width: 100%;
        display: flex;

        @include themeify {
          border-bottom: 1px solid themed('tableBorderColor');
        }

        .cell {
          height: inherit;
          min-height: 35px;
          line-height: 25px;
          padding: 5px;
          font-size: 12px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          justify-content: center;
          &.segmentName,
          &.erectMethodName,
          &.segmentLength {
            flex-direction: column;
          }

          @include themeify {
            border-right: 1px solid themed('tableBorderColor');
          }

          &:last-child {
            border: 0;
          }
        }
      }
    }
  }

  #selectDivCable {
    position: fixed;
    will-change: top, left, width;
    z-index: 2;
  }
</style>

@/api/basebiz/BizDictApi
